#include "fileHandler.h"

FileHandler::~FileHandler()
{
    if (outputStream)
    {
        outputStream.close();
    }
}


bool FileHandler::readConfigForWeightVectors(const std::string &fileName,std::vector<std::vector<double> >& weightVectors)
{
    std::string line;
    double value;

    std::ifstream stream(fileName);
    if (stream.is_open())
    {
        while (getline(stream,line))
        {
            std::vector<double> singleWeightVec;
            std::vector<std::string> stringVec = split(line, ',');
            if(stringVec.size() != 11)
            {
                std::cout << "Syntax error in line: " << line << std::endl;
                return false;
            }

            for(auto i = stringVec.begin(); i != stringVec.end(); i++){
                value = atof(i->c_str());
                singleWeightVec.push_back(value);
            }
            weightVectors.push_back(singleWeightVec);
        }
        stream.close();
    }else{
        std::cout << "COULD NOT OPEN " << fileName << "!" << std::endl;
        return false;
    }

    return true;
}


std::vector<std::string>& FileHandler::splitSecond(std::string &s, char delim, std::vector<std::string> &elems){
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> FileHandler::split(std::string &s, char delim) {
    std::vector<std::string> elems;
    splitSecond(s, delim, elems);
    return elems;
}


void FileHandler::updateOriginalWeights(std::vector<double> &weights)
{
    for(auto i = weights.begin(); i != weights.end(); i++)
    {
        outputStream << std::to_string(*i) << ",";
    }
}


void FileHandler::updateResultFile(const std::string& info, std::vector<double> &weights, Result& best,int k, Result& main_result)
{
    outputStream << info << "  " <<  k << "\n";
    for(auto i = weights.begin(); i != weights.end(); i++)
    {
        outputStream << std::to_string(*i) << " ";
    }
    outputStream << "\n";
    if(k != -1)
        outputStream << "best: " << std::to_string(best.correct_ones()/main_result.total_pre[k] )<<  "\n";
    else
        outputStream << "best: " << std::to_string(best.correct_ones())<<  "\n";
}

void FileHandler::nextChapterInResultFile(const std::string& s)
{
    outputStream << "-------- " << s << " -------\n";
}


